﻿//JumbotCms_4.1 Final
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Text;
using Jumbot.DataOper;
using JumbotCms.DataObject;
namespace JumbotCms.Common
{
    /// <summary>
    /// BasicPage 的摘要说明
    /// </summary>
    public class BasicPage : Jumbot.DataOper.UI.PageUI
    {
        public string vbCrlf = "\r\n";//换行符
        public bool NeedLicence = false;//是否需要许可证(对IP访问不限制)
        private string _dbType = "0";
        protected Site site = new Site();
        override protected void OnInit(EventArgs e)
        {
            Server.ScriptTimeout = 90;//默认脚本过期时间
            LoadJumbotCms();
            base.OnInit(e);

        }
        public void LoadJumbotCms()
        {
            this.ConnectDb();
            if (System.Web.HttpContext.Current.Application["System:Info"] == null)
            {
                SetupSystemDate();
            }
            site = (Site)System.Web.HttpContext.Current.Application["System:Info"];
        }
        /// <summary>
        /// 数据库类型,0代表Access,1代表Sql Server
        /// </summary>
        public string DBType
        {
            get { return this._dbType.ToString(); }
            set { this._dbType = value; }
        }
        /// <summary>
        /// 连接数据库
        /// </summary>
        public override void ConnectDb()
        {
            if (doh == null)
            {
                try
                {
                    if (System.Web.HttpContext.Current.Application["Database:dbType"] == null)
                    {
                        System.Web.HttpContext.Current.Application.Lock();
                        System.Web.HttpContext.Current.Application["Database:dbType"] = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/conn", "dbType");
                        System.Web.HttpContext.Current.Application.UnLock();
                    }
                    this._dbType = System.Web.HttpContext.Current.Application["Database:dbType"].ToString();
                    if (this._dbType == "0")
                    {
                        if (System.Web.HttpContext.Current.Application["Database:dbType"] == null)
                        {
                            string dbPath = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/conn", "dbPath");
                            System.Web.HttpContext.Current.Application.Lock();
                            System.Web.HttpContext.Current.Application["Database:dbType"] = dbPath;
                            System.Web.HttpContext.Current.Application.UnLock();
                        }
                        doh = new Jumbot.DataOper.OleDbOperHandler(HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Application["Database:dbType"].ToString()));
                    }
                    else
                    {
                        this._dbType = "1";
                        if (System.Web.HttpContext.Current.Application["Database:dbConnStr"] == null)
                        {
                            string dbConnStr = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/conn", "dbConnStr");
                            System.Web.HttpContext.Current.Application.Lock();
                            System.Web.HttpContext.Current.Application["Database:dbConnStr"] = dbConnStr;
                            System.Web.HttpContext.Current.Application.UnLock();
                        }
                        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(System.Web.HttpContext.Current.Application["Database:dbConnStr"].ToString());
                        doh = new Jumbot.DataOper.SqlDbOperHandler(conn);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 关闭数据库连接
        /// </summary>
        public void CloseDB()
        {
            if (doh != null) doh.Dispose();
        }
        /// <summary>
        /// 转到错误IP页
        /// </summary>
        public void ReturnErrorIP()
        {
            if (IPIsForbiding(GetUserIp()))
            {
                HttpContext.Current.Response.Redirect("~/errorip.aspx");
                HttpContext.Current.Response.End();
            }
        }
        /// <summary>
        /// 生成随机数字字符串
        /// </summary>
        /// <param name="int_NumberLength">数字长度</param>
        /// <returns></returns>
        public string GetRandomNumberString(int int_NumberLength)
        {
            return GetRandomNumberString(int_NumberLength, false);
        }
        /// <summary>
        /// 生成随机数字字符串
        /// </summary>
        /// <param name="int_NumberLength">数字长度</param>
        /// <returns></returns>
        public string GetRandomNumberString(int int_NumberLength, bool onlyNumber)
        {
            Random random = new Random();
            return GetRandomNumberString(int_NumberLength, onlyNumber, random);
        }
        /// <summary>
        /// 生成随机数字字符串
        /// </summary>
        /// <param name="int_NumberLength">数字长度</param>
        /// <returns></returns>
        public string GetRandomNumberString(int int_NumberLength, bool onlyNumber, Random random)
        {
            string strings = "123456789";
            if (!onlyNumber) strings += "abcdefghjkmnpqrstuvwxyz";
            char[] chars = strings.ToCharArray();
            string returnCode = string.Empty;
            for (int i = 0; i < int_NumberLength; i++)
                returnCode += chars[random.Next(0, chars.Length)].ToString();
            return returnCode;
        }
        public void DownloadFile(string _filePath)
        {
            Response.Clear();
            bool success = true;
            if (_filePath.StartsWith("http://") || _filePath.StartsWith("https://") || _filePath.StartsWith("ftp://"))
                Response.Redirect(_filePath);
            else if (!Jumbot.Common.DirFile.FileExists(_filePath))
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/_data/log/nofile_" + DateTime.Now.ToString("yyyyMMdd") + ".log"), true, System.Text.Encoding.UTF8);
                sw.WriteLine(System.DateTime.Now.ToString());
                sw.WriteLine("\tIP 地 址：" + GetUserIp());
                sw.WriteLine("\t访 问 者：" + ThisUser());
                sw.WriteLine("\t浏 览 器：" + HttpContext.Current.Request.Browser.Browser + HttpContext.Current.Request.Browser.Version);
                sw.WriteLine("\t下载页面：" + ServerUrl() + GetCurrentUrl());
                sw.WriteLine("\t无效文件：" + _filePath);
                sw.WriteLine("---------------------------------------------------------------------------------------------------");
                sw.Close();
                Response.Write("指定的文件不存在,请通知管理员");
            }
            else
            {
                success = Jumbot.Common.DirFile.DownloadFile(Request, Response, Server.MapPath(_filePath), 1024000);
                if (!success)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/_data/log/downerror_" + DateTime.Now.ToString("yyyyMMdd") + ".log"), true, System.Text.Encoding.UTF8);
                    sw.WriteLine(System.DateTime.Now.ToString());
                    sw.WriteLine("\tIP 地 址：" + GetUserIp());
                    sw.WriteLine("\t访 问 者：" + ThisUser());
                    sw.WriteLine("\t浏 览 器：" + HttpContext.Current.Request.Browser.Browser + HttpContext.Current.Request.Browser.Version);
                    sw.WriteLine("\t下载页面：" + ServerUrl() + GetCurrentUrl());
                    sw.WriteLine("\t失败文件：" + _filePath);
                    sw.WriteLine("---------------------------------------------------------------------------------------------------");
                    sw.Close();
                    Response.Redirect(_filePath);
                }
            }
            Response.End();
        }
        /// <summary>
        /// 当前访客
        /// </summary>
        public string ThisUser()
        {
            if (Jumbot.Common.Cookie.GetValue(site.CookiePrev + "user") != null)
                return Jumbot.Common.Cookie.GetValue(site.CookiePrev + "user", "name");
            else
                return "游客";
        }
        /// <summary>
        /// 简单的防止站外提交表单
        /// 仿一般黑客，防不住高手
        /// </summary>
        /// <returns></returns>
        public bool CheckFormUrl()
        {
            if (q("debugkey") == site.DebugKey) return true;
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                SaveVisitLog(2, 0);
                return false;
            }
            if ((HttpContext.Current.Request.UrlReferrer.Host) != (HttpContext.Current.Request.Url.Host))
            {
                SaveVisitLog(2, 0);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 处理过程完成
        /// </summary>
        /// <param name="pageMsg">页面提示信息</param>
        /// <param name="go2Url">如果倒退步数为0，就转到该地址</param>
        /// <param name="BackStep">倒退步数</param>
        protected void FinalMessage(string pageMsg, string go2Url, int BackStep)
        {
            FinalMessage(pageMsg, go2Url, BackStep, 2);
        }
        /// <summary>
        /// 处理过程完成
        /// </summary>
        /// <param name="pageMsg">页面提示信息</param>
        /// <param name="go2Url">如果倒退步数为0，就转到该地址</param>
        /// <param name="BackStep">倒退步数</param>
        /// <param name="BackStep">自动转向的秒数</param>
        protected void FinalMessage(string pageMsg, string go2Url, int BackStep, int Seconds)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<html>" + "\r\n");
            sb.Append("<head>" + "\r\n");
            sb.Append("    <title>系统提示 - " + site.Name + "</title>" + "\r\n");
            sb.Append("    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" + "\r\n");
            sb.Append("<script language=\"javascript\">" + "\r\n");
            sb.Append("var secs=" + Seconds + ";" + "\r\n");
            sb.Append("for(i=1;i<=secs;i++) " + "\r\n");
            sb.Append("{ window.setTimeout(\"update(\" + i + \")\", i * 1000);} " + "\r\n");
            sb.Append("function update(num) " + "\r\n");
            sb.Append("{ " + "\r\n");
            sb.Append("if(num == secs) " + "\r\n");
            if (BackStep > 0)
                sb.Append("{ history.go(" + (0 - BackStep) + "); } " + "\r\n");
            else
            {
                if (go2Url != "")
                    sb.Append("{ self.location.href='" + go2Url + "'; } " + "\r\n");
                else
                    sb.Append("{window.close();} " + "\r\n");
            }
            sb.Append("else " + "\r\n");
            sb.Append("{ } " + "\r\n");
            sb.Append("}" + "\r\n");
            sb.Append("</script>" + "\r\n");
            sb.Append("<base target='_self' />" + "\r\n");
            sb.Append("</head>" + "\r\n");
            sb.Append("<body>" + "\r\n");
            sb.Append("<center>" + "\r\n");
            sb.Append("    <br />" + "\r\n");
            sb.Append("    <div style='width:400px;padding-top:4px;margin-top:1px;height:24;font-size:10pt;border-top:1px #B4E0F7 solid;border-left:1px #B4E0F7 solid;border-right:1px #B4E0F7 solid;border-right:1px #B4E0F7 solid;background:#F5FBFF;font-weight:bold;color:#2259A6'>提示信息</div>" + "\r\n");
            sb.Append("    <div style='width:400px;height:100;font-size:10pt;background:#F5FBFF;border:1px #B4E0F7 solid'><br />" + "\r\n");
            sb.Append("    <br />" + pageMsg + "<br /><br />" + "\r\n");
            if (BackStep > 0)
                sb.Append("        <a href=\"javascript:history.go(" + (0 - BackStep) + ")\">如果您的浏览器没有自动跳转，请点击这里</a>" + "\r\n");
            else
                sb.Append("        <a href=\"" + go2Url + "\">如果您的浏览器没有自动跳转，请点击这里</a>" + "\r\n");
            sb.Append("        <br />" + "\r\n");
            sb.Append("    </div>" + "\r\n");
            sb.Append("</center>" + "\r\n");
            sb.Append("</body>" + "\r\n");
            sb.Append("</html>" + "\r\n");
            HttpContext.Current.Response.Write(sb.ToString());
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// 当前页码
        /// </summary>
        public int Int_ThisPage()
        {
            int _page = Str2Int(q("page"), 0) < 1 ? 1 : Str2Int(q("page"), 0);
            return _page;
        }

        /// <summary>
        /// 执行Sql脚本文件
        /// </summary>
        /// <param name="pathToScriptFile">物理路径</param>
        /// <returns></returns>
        public bool ExecuteSqlInFile(string pathToScriptFile)
        {
            if (this._dbType == "1")
                return Jumbot.Common.ExecuteSqlBlock.Go("1", System.Web.HttpContext.Current.Application["Database:dbConnStr"].ToString(), pathToScriptFile);
            else
                return Jumbot.Common.ExecuteSqlBlock.Go("0", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(System.Web.HttpContext.Current.Application["Database:dbType"].ToString()), pathToScriptFile);
        }
        /// <summary>
        /// 附加被选择的字段
        /// </summary>
        /// <param name="_fields">格式为[字段1],[字段2]</param>
        /// <returns></returns>
        public static string JoinFields(string _fields)
        {
            if (_fields.Trim().Length == 0)
                return "";
            else
                return "," + _fields;
        }
        /// <summary>
        /// 检测指定IP地址是否已受到屏蔽
        /// </summary>
        /// <param name="IP地址">要检测的IP地址</param>
        /// <returns>是否属于已屏蔽的IP</returns>
        public bool IPIsForbiding(string IP)
        {
            long ip = Jumbot.Common.staticFunction.IP2Long(System.Net.IPAddress.Parse(IP));
            doh.Reset();
            if (DBType == "0")
            {
                doh.ConditionExpress = "StartIP<=" + ip.ToString() + " and EndIP>=" + ip.ToString() + " AND datediff('d','" + DateTime.Now.ToShortDateString() + "',ExpireDate)>0";
            }
            else
            {
                doh.ConditionExpress = "StartIP<=" + ip.ToString() + " and EndIP>=" + ip.ToString() + " AND datediff(d,'" + DateTime.Now.ToShortDateString() + "',ExpireDate)>0";
            }
            if (doh.Exist("jcms_normal_forbidip"))
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 页面访问超时后记录日志
        /// </summary>
        /// <param name="_second">超时秒数</param>
        public void SavePageLog(int _second)
        {
            SaveVisitLog(1, _second);
        }
        /// <summary>
        /// 保存访问日志
        /// </summary>
        /// <param name="_type">1代表超时,2代表非法</param>
        /// <param name="_second">超时秒数</param>
        public void SaveVisitLog(int _type, int _second)
        {
            if (_type == 1)
            {
                Single s = (Single)DateTime.Now.Subtract(HttpContext.Current.Timestamp).TotalSeconds;
                if (s > _second)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/_data/log/timeout_" + DateTime.Now.ToString("yyyyMMdd") + ".log"), true, System.Text.Encoding.UTF8);
                    sw.WriteLine(System.DateTime.Now.ToString());
                    sw.WriteLine("\tIP 地 址：" + GetUserIp());
                    sw.WriteLine("\t访 问 者：" + ThisUser());
                    sw.WriteLine("\t浏 览 器：" + HttpContext.Current.Request.Browser.Browser + HttpContext.Current.Request.Browser.Version);
                    sw.WriteLine("\t耗    时：" + ((Single)DateTime.Now.Subtract(HttpContext.Current.Timestamp).TotalSeconds).ToString("0.000") + "秒");
                    sw.WriteLine("\t地    址：" + ServerUrl() + GetCurrentUrl());
                    sw.WriteLine("---------------------------------------------------------------------------------------------------");
                    sw.Close();
                    sw.Dispose();
                }
            }
            else
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath("~/_data/log/hacker_" + DateTime.Now.ToString("yyyyMMdd") + ".log"), true, System.Text.Encoding.UTF8);
                sw.WriteLine(System.DateTime.Now.ToString());
                sw.WriteLine("\tIP 地 址：" + GetUserIp());
                sw.WriteLine("\t访 问 者：" + ThisUser());
                sw.WriteLine("\t浏 览 器：" + HttpContext.Current.Request.Browser.Browser + HttpContext.Current.Request.Browser.Version);
                sw.WriteLine("\t来    源：" + ServerUrl() + GetRefererUrl());
                sw.WriteLine("\t地    址：" + ServerUrl() + GetCurrentUrl());
                sw.WriteLine("---------------------------------------------------------------------------------------------------");
                sw.Close();
                sw.Dispose();
            }
        }
        /// <summary>
        /// 服务器地址
        /// </summary>
        /// <returns></returns>
        protected string ServerUrl()
        {
            if (HttpContext.Current.Request.ServerVariables["Server_Port"].ToString() == "80")
                return "http://" + HttpContext.Current.Request.Url.Host;
            else
                return "http://" + HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.ServerVariables["Server_Port"].ToString();
        }

        /// <summary>
        /// 根据配置对指定字符串进行 MD5 32加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        protected string GetHash32(string s)
        {
            s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString();
            return s.ToLower();
        }
        /// <summary>
        /// 根据配置对指定字符串进行 MD5 16加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        protected string GetHash16(string s)
        {
            s = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5").ToString();
            return s.ToLower().Substring(8, 16);
        }
        /// <summary>
        /// 产生随机数字字符串
        /// </summary>
        /// <returns></returns>
        public string RandomStr(int Num)
        {
            int number;
            char code;
            string returnCode = String.Empty;

            Random random = new Random();

            for (int i = 0; i < Num; i++)
            {
                number = random.Next();
                code = (char)('0' + (char)(number % 10));
                returnCode += code.ToString();
            }
            return returnCode;
        }
        /// <summary>
        /// 初始化系统信息
        /// </summary>
        protected void SetupSystemDate()
        {
            CheckLicence();
            site = new Site(doh);
            System.Web.HttpContext.Current.Application.Lock();
            System.Web.HttpContext.Current.Application["System:Info"] = site;
            System.Web.HttpContext.Current.Application.UnLock();
        }
        /// <summary>
        /// 验证授权信息
        /// </summary>
        protected void CheckLicence()
        {
            if (!NeedLicence) return;
            string _lUserName = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/licence", "UserName");
            string _lDomainName = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/licence", "DomainName");
            string _lMachineCode = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/licence", "MachineCode");
            string _lSerialCode = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/licence", "SerialCode");
            if (!Jumbot.Common.Licence.IsAuthorized(_lUserName, _lDomainName, _lMachineCode, _lSerialCode))
                Response.Redirect("~/licence.aspx");
        }
        /// <summary>
        /// 输出js
        /// </summary>
        /// <param name="sType"></param>
        /// <param name="jsContent"></param>
        protected void WriteJs(string sType, string jsContent)
        {
            if (sType == "-1")
                Page.ClientScript.RegisterStartupScript(this.GetType(), "writejs", jsContent, true);
            else
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "writejs", jsContent, true);

        }
        /// <summary>
        /// 输出json结果
        /// </summary>
        /// <param name="success">是否操作成功,0表示失败;1表示成功</param>
        /// <param name="str">输出字符串</param>
        /// <returns></returns>
        protected string JsonResult(int success, string str)
        {
            return "{result :\"" + success.ToString() + "\",returnval :\"" + str + "\"}";

        }
        /// <summary>
        /// 高光显示关键字
        /// </summary>
        /// <param name="PageStr">内容</param>
        /// <param name="keys">关键字</param>
        /// <returns></returns>
        protected string p__HighLight(string PageStr, string keys)
        {
            string[] key = keys.Split(new string[] { " " }, StringSplitOptions.None);
            for (int i = 0; i < key.Length; i++)
            {
                PageStr = PageStr.Replace(key[i].Trim(), "<font color=#C60A00>" + key[i].Trim() + "</font>");
            }
            return PageStr;
        }
        /// <summary>
        /// 获得逐级缩进的栏目名
        /// </summary>
        /// <param name="sName">栏目名</param>
        /// <param name="sCode">栏目code</param>
        /// <returns>逐级缩进的栏目名</returns>
        public string getListName(string sName, string sCode)
        {
            int Level = (sCode.Length / 4 - 1);
            string sStr = "";
            if (Level > 0)
            {
                for (int i = 0; i < Level; i++)
                    sStr += "├－";
            }
            return sStr + sName;
        }

        /// <summary>
        /// 通用分页
        /// </summary>
        /// <param name="mode">支持1=simple,2=normal,3=full</param>
        /// <param name="countNum">记录数</param>
        /// <param name="currentPage">第几页</param>
        /// <param name="FieldName">参数名</param>
        /// <param name="FieldValue">参数值</param>
        /// <returns></returns>
        public string PageList(int mode, int countNum, int PSize, int currentPage, string[] FieldName, string[] FieldValue)
        {
            string Script_Name = HttpContext.Current.Request.ServerVariables["Script_Name"].ToString();
            string pString = "";
            for (int i = 0; i < FieldName.Length; i++)
            {
                pString += FieldName[i].ToString() + "=" + FieldValue[i].ToString() + "&";
            }
            string Http = Script_Name + "?" + pString + "page=<#page#>";
            return Jumbot.Common.HtmlPager.GetPageBar(mode, "html", 0, countNum, PSize, currentPage, Http);
        }
        /// <summary>
        /// 智能分页
        /// </summary>
        /// <param name="mode">支持1=simple,2=normal,3=full</param>
        /// <param name="countNum">记录数</param>
        /// <param name="currentPage">第几页</param>
        /// <returns></returns>
        public string AutoPageBar(int mode, int stepNum, int countNum, int PSize, int currentPage)
        {
            string Http = GetUrlPrefix() + "<#page#>";
            return Jumbot.Common.HtmlPager.GetPageBar(mode, "html", stepNum, countNum, PSize, currentPage, Http);
        }
        /// <summary>
        /// 当前地址前缀
        /// </summary>
        public string GetUrlPrefix()
        {
            HttpRequest Request = HttpContext.Current.Request;
            string strUrl;
            strUrl = HttpContext.Current.Request.ServerVariables["Url"];
            if (HttpContext.Current.Request.QueryString.Count == 0) //如果无参数
                return strUrl + "?page=";
            else
            {
                //if (Jumbot.Common.Strings.Left(HttpContext.Current.Request.ServerVariables["Query_String"], 5) == "page=")//只有页参数
                if (HttpContext.Current.Request.ServerVariables["Query_String"].StartsWith("page=", StringComparison.OrdinalIgnoreCase))//只有页参数
                    return strUrl + "?page=";
                else
                {
                    string[] strUrl_left;
                    strUrl_left = HttpContext.Current.Request.ServerVariables["Query_String"].Split(new string[] { "page=" }, StringSplitOptions.None);
                    if (strUrl_left.Length == 1)//没有页参数
                        return strUrl + "?" + strUrl_left[0] + "&page=";
                    else
                        return strUrl + "?" + strUrl_left[0] + "page=";
                }

            }

        }
        /// <summary>
        /// 获得翻页Bar，适合js和html
        /// </summary>
        /// <param name="mode">支持1=simple,2=normal,3=full</param>
        /// <param name="stype"></param>
        /// <param name="countNum"></param>
        /// <param name="PSize"></param>
        /// <param name="currentPage"></param>
        /// <param name="Http"></param>
        /// <returns></returns>
        public string getPageBar(int mode, string stype, int stepNum, int countNum, int PSize, int currentPage, string HttpN)
        {
            return Jumbot.Common.HtmlPager.GetPageBar(mode, stype, stepNum, countNum, PSize, currentPage, HttpN);
        }
        /// <summary>
        /// 获得翻页Bar，适合js和html
        /// </summary>
        /// <param name="mode">支持1=simple,2=normal,3=full</param>
        /// <param name="stype"></param>
        /// <param name="stepNum"></param>
        /// <param name="countNum"></param>
        /// <param name="PSize"></param>
        /// <param name="currentPage"></param>
        /// <param name="Http1"></param>
        /// <param name="HttpM"></param>
        /// <param name="HttpN"></param>
        /// <param name="limitPage"></param>
        /// <returns></returns>
        public string getPageBar(int mode, string stype, int stepNum, int countNum, int PSize, int currentPage, string Http1, string HttpM, string HttpN, int limitPage)
        {
            return Jumbot.Common.HtmlPager.GetPageBar(mode, stype, stepNum, countNum, PSize, currentPage, Http1, HttpM, HttpN, limitPage);
        }

        /// <summary>
        /// 获取querystring
        /// </summary>
        /// <param name="s">参数名</param>
        /// <returns>返回值</returns>
        public string q(string s)
        {
            if (HttpContext.Current.Request.QueryString[s] != null && HttpContext.Current.Request.QueryString[s] != "")
            {
                return Jumbot.Common.Strings.SafetyStr(HttpContext.Current.Request.QueryString[s].ToString());
            }
            return string.Empty;
        }

        /// <summary>
        /// 获取post得到的参数
        /// </summary>
        /// <param name="s">参数名</param>
        /// <returns>返回值</returns>
        public string f(string s)
        {
            if (HttpContext.Current.Request.Form[s] != null && HttpContext.Current.Request.Form[s] != "")
            {
                return HttpContext.Current.Request.Form[s].ToString();
            }
            return string.Empty;
        }

        /// <summary>
        /// 返回非负整数，默认为t
        /// </summary>
        /// <param name="s">参数值</param>
        /// <returns>返回值</returns>
        public int Str2Int(string s, int t)
        {
            return Jumbot.Common.Validator.StrToInt(s, t);
        }

        /// <summary>
        /// 返回非负整数，默认为0
        /// </summary>
        /// <param name="s">参数值</param>
        /// <returns>返回值</returns>
        public int Str2Int(string s)
        {
            return Str2Int(s, 0);
        }

        /// <summary>
        /// 返回非空字符串，默认为"0"
        /// </summary>
        /// <param name="s">参数值</param>
        /// <returns>返回值</returns>
        public string Str2Str(string s)
        {
            return Jumbot.Common.Validator.StrToInt(s, 0).ToString();
        }
        /// <summary>
        /// 字符串长度
        /// </summary>
        protected int GetStringLen(string str)
        {
            byte[] bs = System.Text.Encoding.Default.GetBytes(str);
            return bs.Length;
        }
        /// <summary>
        /// 字符串截断
        /// </summary>
        /// <param name="str"></param>
        /// <param name="Length">以汉字计算，比如Length为100表示取200个字符，100个汉字</param>
        /// <returns></returns>
        protected string GetCutString(string str, int Length)
        {
            Length *= 2;
            byte[] bs = System.Text.Encoding.Default.GetBytes(str);
            if (bs.Length <= Length)
            {
                return str;
            }
            else
            {
                return System.Text.Encoding.Default.GetString(bs, 0, Length);
            }
        }
        #region 保存Js文件
        /// <summary>
        /// 保存js文件
        /// </summary>
        /// <param name="TxtStr">文件内容</param>
        /// <param name="TxtFile">输出路径，物理路径</param>
        protected void SaveJsFile(string TxtStr, string TxtFile)
        {
            SaveJsFile(TxtStr, TxtFile, "2");
        }
        /// <summary>
        /// 保存js文件
        /// </summary>
        /// <param name="TxtStr">文件内容</param>
        /// <param name="TxtFile">输出路径，物理路径</param>
        /// <param name="Edcode">编码：1=gb2312,2=utf-8,3=unicode</param>
        protected void SaveJsFile(string TxtStr, string TxtFile, string Edcode)
        {
            System.Text.Encoding FileType = System.Text.Encoding.Default;
            switch (Edcode)
            {
                case "3":
                    FileType = System.Text.Encoding.Unicode;
                    break;
                case "2":
                    FileType = System.Text.Encoding.UTF8;
                    break;
                case "1":
                    FileType = System.Text.Encoding.GetEncoding("GB2312");
                    break;
            }
            Jumbot.Common.DirFile.CreateFolder(Jumbot.Common.DirFile.GetFolderPath(false, TxtFile));
            System.IO.StreamWriter sw = new System.IO.StreamWriter(TxtFile, false, FileType);
            sw.Write("/*系统于 " + System.DateTime.Now.ToString() + " 自动生成,请勿私自改动*/\r\n" + TxtStr);
            sw.Close();
        }
        #endregion
        #region 保存Css文件
        /// <summary>
        /// 保存Css文件
        /// </summary>
        /// <param name="TxtStr">文件内容</param>
        /// <param name="TxtFile">输出路径，物理路径</param>
        protected void SaveCssFile(string TxtStr, string TxtFile)
        {
            SaveCssFile(TxtStr, TxtFile, "2");
        }
        /// <summary>
        /// 保存Css文件
        /// </summary>
        /// <param name="TxtStr">文件内容</param>
        /// <param name="TxtFile">输出路径，物理路径</param>
        /// <param name="Edcode">编码：1=gb2312,2=utf-8,3=unicode</param>
        protected void SaveCssFile(string TxtStr, string TxtFile, string Edcode)
        {
            System.Text.Encoding FileType = System.Text.Encoding.Default;
            switch (Edcode)
            {
                case "3":
                    FileType = System.Text.Encoding.Unicode;
                    break;
                case "2":
                    FileType = System.Text.Encoding.UTF8;
                    break;
                case "1":
                    FileType = System.Text.Encoding.GetEncoding("GB2312");
                    break;
            }
            Jumbot.Common.DirFile.CreateFolder(Jumbot.Common.DirFile.GetFolderPath(false, TxtFile));
            System.IO.StreamWriter sw = new System.IO.StreamWriter(TxtFile, false, FileType);
            sw.Write("/*系统于 " + System.DateTime.Now.ToString() + " 自动生成,请勿私自改动*/\r\n" + TxtStr);
            sw.Close();
        }
        #endregion
        #region 处理Cache文件
        /// <summary>
        /// 读取Cache文件并保存到Html文件
        /// </summary>
        /// <param name="CacheStr">缓存内容</param>
        /// <param name="OutFile">输出路径，物理路径</param>
        protected void SaveCacheFile(string CacheStr, string OutFile)
        {
            SaveCacheFile(CacheStr, OutFile, "2");
        }
        /// <summary>
        /// 保存Cache文件
        /// </summary>
        /// <param name="CacheStr">缓存内容</param>
        /// <param name="OutFile">输出路径，物理路径</param>
        /// <param name="Edcode">编码：1=gb2312,2=utf-8,3=unicode</param>
        protected void SaveCacheFile(string CacheStr, string OutFile, string Edcode)
        {
            System.Text.Encoding FileType = System.Text.Encoding.Default;
            switch (Edcode)
            {
                case "3":
                    FileType = System.Text.Encoding.Unicode;
                    break;
                case "2":
                    FileType = System.Text.Encoding.UTF8;
                    break;
                case "1":
                    FileType = System.Text.Encoding.GetEncoding("GB2312");
                    break;
            }
            Jumbot.Common.DirFile.CreateFolder(Jumbot.Common.DirFile.GetFolderPath(false, OutFile));
            try
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(OutFile, false, FileType);
                //下面这行测试所用，可以注释
                //CacheStr += "\r\n<!--Published " + System.DateTime.Now.ToString() + "-->";
                sw.Write(CacheStr);
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 链接到页面
        /// <summary>
        /// 链接到频道首页
        /// </summary>
        public string Go2Channel(bool ishtml, string ccId)
        {

            GetLinkPath gl = new GetLinkPath();
            return gl.Channel(ishtml, doh, ccId);
        }
        /// <summary>
        /// 链接到内容页
        /// </summary>
        public string Go2View(DbOperHandler doh, int page, bool ishtml, string ccId, string vId)
        {
            GetLinkPath gl = new GetLinkPath();
            return gl.View(page, ishtml, doh, ccId, vId);
        }
        /// <summary>
        /// 链接到栏目页
        /// </summary>
        public string Go2Class(DbOperHandler doh, int page, bool ishtml, string ccId, string cId)
        {
            GetLinkPath gl = new GetLinkPath();
            return gl.Class(page, ishtml, doh, ccId, cId);
        }
        /// <summary>
        /// 链接到RSS页
        /// </summary>
        public string Go2Rss(DbOperHandler doh, int page, bool ishtml, string ccId, string cId)
        {
            GetLinkPath gl = new GetLinkPath();
            return gl.Rss(page, ishtml, doh, ccId, cId);
        }
        #endregion

        /// <summary>
        /// 管理员退出登录
        /// </summary>
        public void ChkAdminLogout()
        {
            if (Jumbot.Common.Cookie.GetValue(site.CookiePrev + "admin") != null)
            {
                Jumbot.Common.Cookie.Del(site.CookiePrev + "admin", site.CookieDomain, site.CookiePath);
            }
        }
        /// <summary>
        /// 验证管理员登录
        /// </summary>
        /// <param name="_adminname">登录名</param>
        /// <param name="_adminpass">密码</param>
        /// <param name="iExpires">保存信息的天数</param>
        /// <returns></returns>
        public string ChkAdminLogin(string _adminname, string _adminpass, int iExpires)
        {
            _adminname = _adminname.Replace("\'", "");
            doh.Reset();
            doh.ConditionExpress = "adminname=@adminname and adminstate=1";
            doh.AddConditionParameter("@adminname", _adminname);
            string _adminid = Str2Str(doh.GetValue("jcms_normal_user", "adminid").ToString());
            if (_adminid != "0")
            {
                Admin _Admin = new Admin();
                _Admin.GetAllColumn(_adminid, doh);
                if (_Admin.AdminPass.Length == 16)//老密码
                {
                    if (_Admin.AdminPass != GetHash16(_adminpass))
                        return "密码错误";
                }
                else
                {
                    if (_Admin.AdminPass != GetHash32(_adminpass))
                        return "密码错误";
                }
                string _adminFolder = _Admin.AdminFolder;
                string _adminCookiess = "c" + (new Random().Next(10000000, 99999999)).ToString();
                //设置Cookies
                System.Collections.Specialized.NameValueCollection myCol = new System.Collections.Specialized.NameValueCollection();
                myCol.Add("id", _adminid);
                myCol.Add("name", _adminname);
                myCol.Add("password", GetHash32(_adminpass));
                myCol.Add("folder", _adminFolder);
                myCol.Add("cookies", _adminCookiess);
                Jumbot.Common.Cookie.SetObj(site.CookiePrev + "admin", iExpires, myCol, site.CookieDomain, site.CookiePath);

                //更新管理员登陆信息
                doh.Reset();
                doh.ConditionExpress = "adminid=@adminid and adminstate=1";
                doh.AddConditionParameter("@adminid", _adminid);
                if (_Admin.AdminPass.Length == 16)//老密码
                    doh.AddFieldItem("AdminPass", GetHash32(_adminpass));
                doh.AddFieldItem("Cookiess", _adminCookiess);
                doh.AddFieldItem("LastTime2", DateTime.Now.ToString());
                doh.AddFieldItem("LastIp2", GetUserIp());
                doh.Update("jcms_normal_user");
                return "ok";
            }
            else
                return "无此用户";
        }
        /// <summary>
        /// 频道管理权限菜单
        /// </summary>
        /// <returns></returns>
        protected string[] powerMenu()
        {
            //实际权限为前面加频道ID
            string[] menu = new string[30];
            menu[0] = "内容浏览";
            menu[1] = "内容录入";
            menu[2] = "内容修改";
            menu[3] = "内容删除";
            menu[4] = "内容审核";
            menu[5] = "内容推荐";
            menu[6] = "内容移动";
            menu[7] = "栏目管理";
            menu[8] = "前台更新";

            return menu;
        }
        /// <summary>
        /// User退出登录
        /// </summary>
        /// <param name="_userkey"></param>
        /// <returns></returns>
        public bool ChkUserLogout(string _userkey)
        {
            ChkAdminLogout();
            if (Jumbot.Common.Cookie.GetValue(site.CookiePrev + "user") != null)
            {
                if (Jumbot.Common.Cookie.GetValue(site.CookiePrev + "user", "password").Substring(4, 8) == _userkey)
                {
                    Jumbot.Common.Cookie.Del(site.CookiePrev + "user", site.CookieDomain, site.CookiePath);
                    if (site.ForumPath != "")
                    {
                        //退出社区
                        Jumbot.API.Discuz.Command.LoginOut();
                    }
                    return true;
                }
                else
                    return false;
            }
            return false;
        }
        /// <summary>
        /// 验证User登录
        /// </summary>
        /// <param name="_username">登录名：同时支持用户名和邮箱</param>
        /// <param name="_userpass">密码</param>
        /// <param name="iExpires">保存信息的天数</param>
        /// <returns></returns>
        public string ChkUserLogin(string _username, string _userpass, int iExpires)
        {
            _username = _username.Replace("\'", "");
            doh.Reset();
            //doh.ConditionExpress = "username='" + _username + "' or email='" + _username + "'";//支持邮件登陆，不推荐
            doh.ConditionExpress = "username=@username";
            doh.AddConditionParameter("@username", _username);
            string _userid = Str2Str(doh.GetValue("jcms_normal_user", "id").ToString());
            if (_userid != "0")
            {
                User _User = new User();
                _User.GetAllColumn(_userid, doh);
                if (_User.UserPass.Length == 16)//老密码
                {
                    if (_User.UserPass != GetHash16(_userpass))
                        return "密码错误";
                }
                else
                {
                    if (_User.UserPass != GetHash32(_userpass))
                        return "密码错误";
                }
                if (_User.State != 1)
                    return "尚未激活";
                doh.Reset();
                doh.SqlCmd = "SELECT [id],[GroupName],[IsLogin],[Setting] FROM [jcms_normal_usergroup] WHERE [Id]=" + _User.Group;
                DataTable dtUserGroup = doh.GetDataTable();
                if (dtUserGroup.Rows.Count == 0)
                    return "尚未激活";
                if (dtUserGroup.Rows[0]["IsLogin"].ToString() != "1")
                    return "尚未激活";
                string _userGroupid = dtUserGroup.Rows[0]["Id"].ToString();
                string _userGroupname = dtUserGroup.Rows[0]["GroupName"].ToString();
                string _userSetting = dtUserGroup.Rows[0]["Setting"].ToString();
                dtUserGroup.Clear();
                dtUserGroup.Dispose();
                string _userCookies = "c" + (new Random().Next(10000000, 99999999)).ToString();
                //设置Cookies
                System.Collections.Specialized.NameValueCollection myCol = new System.Collections.Specialized.NameValueCollection();
                myCol.Add("id", _userid);
                myCol.Add("name", _User.UserName);
                myCol.Add("password", _User.UserPass);
                myCol.Add("groupid", _userGroupid);
                myCol.Add("groupname", _userGroupname);
                myCol.Add("setting", _userSetting);
                myCol.Add("cookies", _userCookies);
                Jumbot.Common.Cookie.SetObj(site.CookiePrev + "user", 60 * 60 * 24 * iExpires, myCol, site.CookieDomain, site.CookiePath);

                //更新User登陆信息
                doh.Reset();
                doh.ConditionExpress = "id=@id and state=1";
                doh.AddConditionParameter("@id", _userid);
                if (_User.UserPass.Length == 16)//老密码
                    doh.AddFieldItem("UserPass", GetHash32(_userpass));
                doh.AddFieldItem("Cookies", _userCookies);
                doh.AddFieldItem("LastTime", DateTime.Now.ToString());
                doh.AddFieldItem("LastIp", GetUserIp());
                doh.AddFieldItem("MailSign", "");
                doh.Update("jcms_normal_user");
                if (site.ForumPath != "")
                {
                    bool _AutoLogining = false;
                    string _ForumAutoRegister = Jumbot.Common.XmlCOM.ReadConfig("~/_data/config/api", "ForumAutoRegister");
                    if (_ForumAutoRegister == "user")//表示自动注册论坛用户
                        _AutoLogining = true;
                    else
                    {
                        if (_User.IsWriter == 1)
                            _AutoLogining = true;
                    }
                    if (_AutoLogining == true)
                    {
                        //登陆社区
                        doh.Reset();
                        doh.ConditionExpress = "id=@id and state=1";
                        doh.AddConditionParameter("@id", _userid);
                        object[] _forumInfo = doh.GetValues("jcms_normal_user", "ForumName,ForumPass");
                        Jumbot.API.Discuz.Command.Login(_forumInfo[0].ToString(), _forumInfo[1].ToString(), iExpires);
                    }
                }
                return "ok";
            }
            else
                return "无此用户";
        }
        /// <summary>
        /// 系统发邮件
        /// </summary>
        /// <param name="_To">收件人</param>
        /// <param name="_Title">标题</param>
        /// <param name="_Body">内容</param>
        /// <param name="_IsHtml">是否支持html</param>
        /// <returns></returns>
        public bool SendMail(string _To, string _Title, string _Body, bool _IsHtml)
        {
            string strXmlFile = HttpContext.Current.Server.MapPath("~/_data/config/mail.config");
            Jumbot.DataOper.XmlControl XmlTool = new Jumbot.DataOper.XmlControl(strXmlFile);
            string _MailFrom = XmlTool.GetText("Mails/System/Address");
            string _MailFromName = XmlTool.GetText("Mails/System/NickName");
            string _MailPwd = XmlTool.GetText("Mails/System/Password");
            string _MailFromHost = XmlTool.GetText("Mails/System/MailHost");
            XmlTool.Dispose();
            _Body += "<br /><a href='" + site.Url + "'>" + site.Name + "</a><br>" + DateTime.Now.ToString("yyyy.MM.dd");
            return Jumbot.Common.Mail.Send(_To, _Title, _Body, _IsHtml, _MailFrom, _MailFromName, _MailPwd, _MailFromHost);
        }
        public bool SendMail(string _To, string _Title, string _Body)
        {
            return SendMail(_To, _Title, _Body, true);
        }
        /// <summary>
        /// 系统发邮件给客服
        /// </summary>
        /// <param name="_Title"></param>
        /// <param name="_Body"></param>
        /// <returns></returns>
        public bool SendServiceMail(string _Title, string _Body)
        {
            string strXmlFile = HttpContext.Current.Server.MapPath("~/_data/config/mail.config");
            Jumbot.DataOper.XmlControl XmlTool = new Jumbot.DataOper.XmlControl(strXmlFile);
            string _ServiceMail = XmlTool.GetText("Mails/Service/Address");
            XmlTool.Dispose();
            return SendMail(_ServiceMail, _Title, _Body);
        }
        /// <summary>
        /// 发站内短信
        /// </summary>
        /// <param name="_Title">标题</param>
        /// <param name="_Content">内容</param>
        /// <param name="_SendUserId">发送人ID</param>
        /// <param name="_ReceiveUserId">接收人ID</param>
        /// <param name="_ReceiveUserName">接收人用户名</param>
        public bool SendMessage(string _Title, string _Content, string _SendUserId, string _ReceiveUserId, string _ReceiveUserName)
        {
            doh.Reset();
            doh.AddFieldItem("Title", _Title);
            doh.AddFieldItem("AddDate", DateTime.Now.ToString());
            doh.AddFieldItem("Content", _Content);
            doh.AddFieldItem("SendIP", GetUserIp());
            doh.AddFieldItem("SendUserId", _SendUserId);
            doh.AddFieldItem("ReceiveUserId", _ReceiveUserId);
            doh.AddFieldItem("ReceiveUserName", _ReceiveUserName);
            doh.AddFieldItem("State", 0);
            doh.Insert("jcms_normal_user_message");
            return true;
        }
        /// <summary>
        /// 系统发站内短信给客服
        /// </summary>
        /// <param name="_Title"></param>
        /// <param name="_Content"></param>
        public bool SendServiceMessage(string _Title, string _Content)
        {
            string strXmlFile = HttpContext.Current.Server.MapPath("~/_data/config/message.config");
            Jumbot.DataOper.XmlControl XmlTool = new Jumbot.DataOper.XmlControl(strXmlFile);
            string _SendUserId = XmlTool.GetText("Messages/System/UserId");
            string _ReceiveUserId = XmlTool.GetText("Messages/Service/UserId");
            string _ReceiveUserName = XmlTool.GetText("Messages/Service/UserName");
            XmlTool.Dispose();
            return SendMessage(_Title, _Content, _SendUserId, _ReceiveUserId, _ReceiveUserName);
        }

        /// <summary>
        /// 发站内通知
        /// </summary>
        /// <param name="_Title">标题</param>
        /// <param name="_Content">内容</param>
        /// <param name="_ReceiveUserId">接收人ID,0表示所有人</param>
        /// <param name="_NoticeType">类型，比如：friend,mtag</param>
        public bool SendNotite(string _Title, string _Content, string _ReceiveUserId, string _NoticeType)
        {
            doh.Reset();
            doh.AddFieldItem("Title", _Title);
            doh.AddFieldItem("AddDate", DateTime.Now.ToString());
            doh.AddFieldItem("Content", _Content);
            doh.AddFieldItem("UserId", _ReceiveUserId);
            doh.AddFieldItem("NoticeType", _NoticeType);
            doh.AddFieldItem("State", 0);
            doh.Insert("jcms_normal_user_notice");
            return true;
        }
        /// <summary>
        /// 通知客服
        /// </summary>
        /// <param name="_Title"></param>
        /// <param name="_Content"></param>
        /// <param name="_type">1表示站内通知,2表示邮件通知</param>
        /// <returns></returns>
        public bool SendServiceNotice(string _Title, string _Content, string _type)
        {
            if (_type == "2")
                return SendServiceMail(_Title, _Content);
            else
                return SendServiceMessage(_Title, _Content);
        }
        /// <summary>
        /// 保存用户日志日志
        /// </summary>
        /// <param name="_uid">会员ID</param>
        /// <param name="_info">保存信息</param>
        /// <param name="_type">操作类型,1=分组移动,2=点数扣除,3=积分增加(2,3为系统操作),4=点数增加,5=VIP升级,6积分扣除(4,5,6为管理员操作)</param>
        protected void SaveUserLog(string _uid, string _info, int _type)
        {
            doh.Reset();
            doh.AddFieldItem("UserId", _uid);
            doh.AddFieldItem("OperInfo", _info);
            doh.AddFieldItem("OperType", _type);
            doh.AddFieldItem("OperTime", DateTime.Now.ToString());
            doh.AddFieldItem("OperIP", GetUserIp());
            doh.Insert("jcms_normal_user_logs");
        }
    }
}
